package com.xdf.zipperdye.service;

import com.xdf.zipperdye.dao.business.ProductMapper;
import com.xdf.zipperdye.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductMapper dao;

    @Override
    public int deleteByPrimaryKey(Integer iid) {
        return dao.deleteByPrimaryKey(iid);
    }

    @Override
    public int insert(Product record) {
        if(check4Insert(record) == false) return 0;
        return dao.insert(record);
    }

    @Override
    public int insertSelective(Product record) {
        if(check4Insert(record) == false) return 0;
        return dao.insertSelective(record);
    }

    @Override
    public Product selectByPrimaryKey(Integer iid) {
        return dao.selectByPrimaryKey(iid);
    }

    @Override
    public int updateByPrimaryKeySelective(Product record) {
        return dao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(Product record) {
        return dao.updateByPrimaryKey(record);
    }

    @Override
    public List<Product> selectAll() {
        return dao.selectAll();
    }

    @Override
    public List<Product> selectBySid(String sid) {
        return dao.selectBySid(sid);
    }

    @Override
    public Boolean isExists(String sid) {
        List<Product> productList = Optional.ofNullable(selectBySid(sid)).orElse(new ArrayList<>());
        return productList.size() > 0 ? true : false;
    }

    // 新增前调用本方法检测合法性，返回true表示可以新增
    public Boolean check4Insert(Product record){
        Assert.notNull(record,"传入数据为空！");
        String sid = Optional.ofNullable(record.getSid()).orElse("");
        if(isExists(sid))
            throw new RuntimeException("编号" + sid + "已经存在！");
        return true;
    }
}
